package net.dodoman.miao;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @author yanping
 * @version 1.0
 * 
 */
public class Reader {
	public static void main(String[] args) throws Exception {
		Reader reader = new Reader();
		reader.saveToDb();
		// reader.delete();
	}

	// 保存到数据库
	private void saveToDb() throws Exception {
		List<String> wordList = getWordList();
		String wholeWord = "", keyWordInc = "";
		Statement stmt = getStatement();
		int id = 1;
		for (String every : wordList) {
			wholeWord = every.substring(0, 4);
			keyWordInc = every.substring(5, 6);
			String insWordSql = "insert into word (WC, KWI) values('"
					+ wholeWord + "','" + keyWordInc + "')";
			String insESql = "insert into example (WEID, WEE) values('" + id
					+ "','" + wholeWord + "')";
			String insExSql = "insert into explain (WEXID, WEXE) values('" + id
					+ "','" + wholeWord + "')";
			stmt.executeUpdate(insWordSql);
			stmt.executeUpdate(insESql);
			stmt.executeUpdate(insExSql);
			id++;
			System.out.println(id);
		}
	}

	// 读取文件到字符串
	private String readFile() throws IOException {
		File read = new File("E:\\Work\\JavaPro\\resources\\Temp.txt");
		BufferedReader br = new BufferedReader(new FileReader(read));
		String temp = null;
		StringBuffer sb = new StringBuffer();
		temp = br.readLine();
		sb.append(temp);
		while (temp != null) {
			temp = br.readLine();
			if (temp != null)
				sb.append(temp);
		}
		br.close();
		temp = sb.toString();
		return temp;
	}

	// 获取需要的词语列表
	private List<String> getWordList() throws IOException {
		Reader reader = new Reader();
		// String text = reader.readFile();
		String[] text = reader.readFile().split("）");
		List<String> wordList = new ArrayList<String>();
		for (String every : text) {
			wordList.add(every);
		}
		return wordList;
	}

	// 获取statement
	private Statement getStatement() throws Exception {
		Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
		String dburl = "jdbc:odbc:miao";// 此为ODBC连接方式
		Connection conn = DriverManager.getConnection(dburl);
		Statement stmt = conn.createStatement();
		return stmt;
	}

	@SuppressWarnings("unused")
	// 清空数据库
	private void delete() throws Exception {
		Statement stmt = getStatement();
		String delSql = "delete from word";
		stmt.executeUpdate(delSql);
	}
}
